<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 1.5.2">
<title>Entity types</title>
<link rel="stylesheet" href="./css/hibernate.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.js"></script>
<script>document.addEventListener('DOMContentLoaded', prettyPrint)</script>
</head>
<body class="article">
<div id="header">
</div>
<div id="content">
<div class="sect2">
<h3 id="entity">Entity types</h3>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="title">Usage of the word <em>entity</em></div>
<div class="paragraph">
<p>The entity type describes the mapping between the actual persistable domain model object and a database table row.
To avoid any confusion with the annotation that marks a given entity type, the annotation will be further referred as <code>@Entity</code>.</p>
</div>
<div class="paragraph">
<p>Throughout this chapter and thereafter, entity types will be simply referred as <em>entity</em>.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="entity-pojo">POJO Models</h4>
<div class="paragraph">
<p>Section <em>2.1 The Entity Class</em> of the <em>JPA 2.1 specification</em> defines its requirements for an entity class.
Applications that wish to remain portable across JPA providers should adhere to these requirements.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The entity class must be annotated with the <code>javax.persistence.Entity</code> annotation (or be denoted as such in XML mapping)</p>
</li>
<li>
<p>The entity class must have a public or protected no-argument constructor. It may define additional constructors as well.</p>
</li>
<li>
<p>The entity class must be a top-level class.</p>
</li>
<li>
<p>An enum or interface may not be designated as an entity.</p>
</li>
<li>
<p>The entity class must not be final. No methods or persistent instance variables of the entity class may be final.</p>
</li>
<li>
<p>If an entity instance is to be used remotely as a detached object, the entity class must implement the <code>Serializable</code> interface.</p>
</li>
<li>
<p>Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.</p>
</li>
<li>
<p>The persistent state of an entity is represented by instance variables, which may correspond to JavaBean-style properties.
An instance variable must be directly accessed only from within the methods of the entity by the entity instance itself.
The state of the entity is available to clients only through the entity’s accessor methods (getter/setter methods) or other business methods.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Hibernate, however, is not as strict in its requirements. The differences from the list above include:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The entity class must have a no-argument constructor, which may be public, protected or package visibility. It may define additional constructors as well.</p>
</li>
<li>
<p>The entity class <em>need not</em> be a top-level class.</p>
</li>
<li>
<p>Technically Hibernate can persist final classes or classes with final persistent state accessor (getter/setter) methods.
However, it is generally not a good idea as doing so will stop Hibernate from being able to generate proxies for lazy-loading the entity.</p>
</li>
<li>
<p>Hibernate does not restrict the application developer from exposing instance variables and reference them from outside the entity class itself.
The validity of such a paradigm, however, is debatable at best.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Let&#8217;s look at each requirement in detail.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-final">Prefer non-final classes</h4>
<div class="paragraph">
<p>A central feature of Hibernate is the ability to load lazily certain entity instance variables (attributes) via runtime proxies.
This feature depends upon the entity class being non-final or else implementing an interface that declares all the attribute getters/setters.
You can still persist final classes that do not implement such an interface with Hibernate,
but you will not be able to use proxies for fetching lazy associations, therefore limiting your options for performance tuning.
For the very same reason, you should also avoid declaring persistent attribute getters and setters as final.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Starting in 5.0 Hibernate offers a more robust version of bytecode enhancement as another means for handling lazy loading.
Hibernate had some bytecode re-writing capabilities prior to 5.0 but they were very rudimentary.
See the <a href="chapters/pc/BytecodeEnhancement.html#BytecodeEnhancement">BytecodeEnhancement</a> for additional information on fetching and on bytecode enhancement.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-constructor">Implement a no-argument constructor</h4>
<div class="paragraph">
<p>The entity class should have a no-argument constructor. Both Hibernate and JPA require this.</p>
</div>
<div class="paragraph">
<p>JPA requires that this constructor be defined as public or protected.
Hibernate, for the most part, does not care about the constructor visibility, as long as the system SecurityManager allows overriding the visibility setting.
That said, the constructor should be defined with at least package visibility if you wish to leverage runtime proxy generation.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-accessors">Declare getters and setters for persistent attributes</h4>
<div class="paragraph">
<p>The JPA specification requires this, otherwise the model would prevent accessing the entity persistent state fields directly from outside the entity itself.</p>
</div>
<div class="paragraph">
<p>Although Hibernate does not require it, it is recommended to follow the JavaBean conventions and define getters and setters for entity persistent attributes.
Nevertheless, you can still tell Hibernate to directly access the entity fields.</p>
</div>
<div class="paragraph">
<p>Attributes (whether fields or getters/setters) need not be declared public.
Hibernate can deal with attributes declared with public, protected, package or private visibility.
Again, if wanting to use runtime proxy generation for lazy loading, the getter/setter should grant access to at least package visibility.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-identifier">Provide identifier attribute(s)</h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Historically this was considered optional.
However, not defining identifier attribute(s) on the entity should be considered a deprecated feature that will be removed in an upcoming release.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The identifier attribute does not necessarily need to be mapped to the column(s) that physically define the primary key.
However, it should map to column(s) that can uniquely identify each row.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>We recommend that you declare consistently-named identifier attributes on persistent classes and that you use a nullable (i.e., non-primitive) type.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The placement of the <code>@Id</code> annotation marks the <a href="chapters/domain/access.html#access">persistence state access strategy</a>.</p>
</div>
<div class="exampleblock">
<div class="title">Example 1. Identifier</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Id
private Integer id;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Hibernate offers multiple identifier generation strategies, see the <a href="chapters/domain/identifiers.html#identifiers">Identifier Generators</a> chapter for more about this topic.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-mapping">Mapping the entity</h4>
<div class="paragraph">
<p>The main piece in mapping the entity is the <code>javax.persistence.Entity</code> annotation.
The <code>@Entity</code> annotation defines just one attribute <code>name</code> which is used to give a specific entity name for use in JPQL queries.
By default, the entity name represents the unqualified name of the entity class itself.</p>
</div>
<div class="exampleblock">
<div class="title">Example 2. Simple <code>@Entity</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Simple {
    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>An entity models a database table.
The identifier uniquely identifies each row in that table.
By default, the name of the table is assumed to be the same as the name of the entity.
To explicitly give the name of the table or to specify other information about the table, we would use the <code>javax.persistence.Table</code> annotation.</p>
</div>
<div class="exampleblock">
<div class="title">Example 3. Simple <code>@Entity</code> with <code>@Table</code></div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
@Table( catalog = "CRM", schema = "purchasing", name = "t_simple" )
public class Simple {
    ...
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="mapping-model-pojo-equalshashcode">Implementing <code>equals()</code> and <code>hashCode()</code></h4>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Much of the discussion in this section deals with the relation of an entity to a Hibernate Session, whether the entity is managed, transient or detached.
If you are unfamiliar with these topics, they are explained in the <a href="chapters/pc/PersistenceContext.html#pc">Persistence Context</a> chapter.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Whether to implement <code>equals()</code> and <code>hashCode()</code> methods in your domain model, let alone how to implement them, is a surprisingly tricky discussion when it comes to ORM.</p>
</div>
<div class="paragraph">
<p>There is really just one absolute case: a class that acts as an identifier must implement equals/hashCode based on the id value(s).
Generally, this is pertinent for user-defined classes used as composite identifiers.
Beyond this one very specific use case and few others we will discuss below, you may want to consider not implementing equals/hashCode altogether.</p>
</div>
<div class="paragraph">
<p>So what&#8217;s all the fuss? Normally, most Java objects provide a built-in <code>equals()</code> and <code>hashCode()</code> based on the object&#8217;s identity, so each new object will be different from all others.
This is generally what you want in ordinary Java programming.
Conceptually however this starts to break down when you start to think about the possibility of multiple instances of a class representing the same data.</p>
</div>
<div class="paragraph">
<p>This is, in fact, exactly the case when dealing with data coming from a database.
Every time we load a specific <code>Person</code> from the database we would naturally get a unique instance.
Hibernate, however, works hard to make sure that does not happen within a given <code>Session</code>.
In fact, Hibernate guarantees equivalence of persistent identity (database row) and Java identity inside a particular session scope.
So if we ask a Hibernate <code>Session</code> to load that specific Person multiple times we will actually get back the same <em>instance</em>:</p>
</div>
<div class="exampleblock">
<div class="title">Example 4. Scope of identity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;

Person p1 = session.get( Person.class,1 );
Person p2 = session.get( Person.class,1 );

// this evaluates to true
assert p1==p2;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Consider another example using a persistent <code>java.util.Set</code>:</p>
</div>
<div class="exampleblock">
<div class="title">Example 5. Set usage with Session-scoped identity</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;

Club club = session.get( Club.class,1 );

Person p1 = session.get( Person.class,1 );
Person p2 = session.get( Person.class,1 );

club.getMembers().add( p1 );
club.getMembers().add( p2 );

// this evaluates to true
assert club.getMembers.size()==1;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>However, the semantic changes when we mix instances loaded from different Sessions:</p>
</div>
<div class="exampleblock">
<div class="title">Example 6. Mixed Sessions</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session1=...;
Session session2=...;

Person p1 = session1.get( Person.class,1 );
Person p2 = session2.get( Person.class,1 );

// this evaluates to false
assert p1==p2;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session1=...;
Session session2=...;

Club club = session1.get( Club.class,1 );

Person p1 = session1.get( Person.class,1 );
Person p2 = session2.get( Person.class,1 );

club.getMembers().add( p1 );
club.getMembers().add( p2 );

// this evaluates to ... well it depends
assert club.getMembers.size()==1;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Specifically the outcome in this last example will depend on whether the <code>Person</code> class implemented equals/hashCode, and, if so, how.</p>
</div>
<div class="paragraph">
<p>Consider yet another case:</p>
</div>
<div class="exampleblock">
<div class="title">Example 7. Sets with transient entities</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;

Club club = session.get( Club.class,1 );

Person p1 = new Person(...);
Person p2 = new Person(...);

club.getMembers().add( p1 );
club.getMembers().add( p2 );

// this evaluates to ... again, it depends
assert club.getMembers.size()==1;</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>In cases where you will be dealing with entities outside of a Session (whether they be transient or detached), especially in cases where you will be using them in Java collections,
you should consider implementing equals/hashCode.</p>
</div>
<div class="paragraph">
<p>A common initial approach is to use the entity&#8217;s identifier attribute as the basis for equals/hashCode calculations:</p>
</div>
<div class="exampleblock">
<div class="title">Example 8. Naive equals/hashCode implementation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Person {

    @Id
    @GeneratedValue
    private Integer id;

    @Override
    public int hashCode() {
        return Objects.hash( id );
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( !( o instanceof Person ) ) {
            return false;
        }
        Person person = (Person) o;
        return Objects.equals( id, person.id );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>It turns out that this still breaks when adding transient instance of <code>Person</code> to a set as we saw in the last example:</p>
</div>
<div class="exampleblock">
<div class="title">Example 9. Still trouble</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;
session.getTransaction().begin();

Club club = session.get( Club.class,1 );

Person p1 = new Person(...);
Person p2 = new Person(...);

club.getMembers().add( p1 );
club.getMembers().add( p2 );

session.getTransaction().commit();

// will actually resolve to false!
assert club.getMembers().contains( p1 );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>The issue here is a conflict between the use of generated identifier, the contract of <code>Set</code> and the equals/hashCode implementations.
<code>Set</code> says that the equals/hashCode value for an object should not change while the object is part of the <code>Set</code>.
But that is exactly what happened here because the equals/hasCode are based on the (generated) id, which was not set until the <code>session.getTransaction().commit()</code> call.</p>
</div>
<div class="paragraph">
<p>Note that this is just a concern when using generated identifiers.
If you are using assigned identifiers this will not be a problem, assuming the identifier value is assigned prior to adding to the <code>Set</code>.</p>
</div>
<div class="paragraph">
<p>Another option is to force the identifier to be generated and set prior to adding to the <code>Set</code>:</p>
</div>
<div class="exampleblock">
<div class="title">Example 10. Forcing identifier generation</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Session session=...;
session.getTransaction().begin();

Club club = session.get( Club.class,1 );

Person p1 = new Person(...);
Person p2 = new Person(...);

session.save( p1 );
session.save( p2 );
session.flush();

club.getMembers().add( p1 );
club.getMembers().add( p2 );

session.getTransaction().commit();

// will actually resolve to false!
assert club.getMembers().contains( p1 );</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>But this is often not feasible.</p>
</div>
<div class="paragraph">
<p>The final approach is to use a "better" equals/hashCode implementation, making use of a natural-id or business-key.</p>
</div>
<div class="exampleblock">
<div class="title">Example 11. Better equals/hashCode with natural-id</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Person {

    @Id
    @GeneratedValue
    private Integer id;

    @NaturalId
    private String ssn;

    protected Person() {
        // Constructor for ORM
    }

    public Person( String ssn ) {
        // Constructor for app
        this.ssn = ssn;
    }

    @Override
    public int hashCode() {
        return Objects.hash( ssn );
    }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }
        if ( !( o instanceof Person ) ) {
            return false;
        }
        Person person = (Person) o;
        return Objects.equals( ssn, person.ssn );
    }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see the question of equals/hashCode is not trivial, nor is there a one-size-fits-all solution.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
<div class="paragraph">
<p>Although using a natural-id is best for <code>equals</code> and <code>hashCode</code>, sometimes you only have the entity identifier that provides a unique constraint.</p>
</div>
<div class="paragraph">
<p>It&#8217;s possible to use the entity identifier for equality check, but it needs a workaround:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>you need to provide a constant value for <code>hashCode</code> so that the hash code value does not change before and after the entity is flushed.</p>
</li>
<li>
<p>you need to compare the entity identifier equality only for non-transient entities.</p>
</li>
</ul>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>For details on mapping the identifier, see the <a href="chapters/domain/identifiers.html#identifiers">Identifiers</a> chapter.</p>
</div>
</div>
<div class="sect3">
<h4 id="entity-pojo-optlock">Mapping optimistic locking</h4>
<div class="paragraph">
<p>JPA defines support for optimistic locking based on either a version (sequential numeric) or timestamp strategy.
To enable this style of optimistic locking simply add the <code>javax.persistence.Version</code> to the persistent attribute that defines the optimistic locking value.
According to JPA, the valid types for these attributes are limited to:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>int</code> or <code>Integer</code></p>
</li>
<li>
<p><code>short</code> or <code>Short</code></p>
</li>
<li>
<p><code>long</code> or <code>Long</code></p>
</li>
<li>
<p><code>java.sql.Timestamp</code></p>
</li>
</ul>
</div>
<div id="entity-pojo-optlock-version-example" class="exampleblock">
<div class="title">Example 12. <code>@Version</code> annotation mapping</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Course {

    @Id
    private Integer id;

    @Version
    private Integer version;
    ...
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Thing {

    @Id
    private Integer id;

    @Version
    private Timestamp ts;

    ...
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity
public class Thing2 {

    @Id
    private Integer id;

    @Version
    private Instant ts;
    ...
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="entity-pojo-optlock-versionless">Versionless optimistic locking</h5>
<div class="paragraph">
<p>Although the default <code>@Version</code> property optimistic locking mechanism is sufficient in many situations,
sometimes, you need rely on the actual database row column values to prevent <strong>lost updates</strong>.</p>
</div>
<div class="paragraph">
<p>Hibernate supports a form of optimistic locking that does not require a dedicated "version attribute".
This is also useful for use with modeling legacy schemas.</p>
</div>
<div class="paragraph">
<p>The idea is that you can get Hibernate to perform "version checks" using either all of the entity&#8217;s attributes, or just the attributes that have changed.
This is achieved through the use of the
<a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/OptimisticLocking.html"><code>@OptimisticLocking</code></a>
annotation which defines a single attribute of type
<a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/annotations/OptimisticLockType.html"><code>org.hibernate.annotations.OptimisticLockType</code></a>.</p>
</div>
<div class="paragraph">
<p>There are 4 available OptimisticLockTypes:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>NONE</code></dt>
<dd>
<p>optimistic locking is disabled even if there is a <code>@Version</code> annotation present</p>
</dd>
<dt class="hdlist1"><code>VERSION</code> (the default)</dt>
<dd>
<p>performs optimistic locking based on a <code>@Version</code> as described above</p>
</dd>
<dt class="hdlist1"><code>ALL</code></dt>
<dd>
<p>performs optimistic locking based on <em>all</em> fields as part of an expanded WHERE clause restriction for the UPDATE/DELETE SQL statements</p>
</dd>
<dt class="hdlist1"><code>DIRTY</code></dt>
<dd>
<p>performs optimistic locking based on <em>dirty</em> fields as part of an expanded WHERE clause restriction for the UPDATE/DELETE SQL statements</p>
</dd>
</dl>
</div>
<div class="sect5">
<h6 id="entity-pojo-optlock-versionless-all">Versionless optimistic locking using <code>OptimisticLockType.ALL</code></h6>
<div id="locking-optimistic-lock-type-all-example" class="exampleblock">
<div class="title">Example 13. <code>OptimisticLockType.ALL</code> mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
@OptimisticLocking(type = OptimisticLockType.ALL)
@DynamicUpdate
public static class Person {

    @Id
    private Long id;

    @Column(name = "`name`")
    private String name;

    private String country;

    private String city;

    @Column(name = "created_on")
    private Timestamp createdOn;

    //Getters and setters are omitted for brevity
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When you need to modify the <code>Person</code> entity above:</p>
</div>
<div id="locking-optimistic-lock-type-all-update-example" class="exampleblock">
<div class="title">Example 14. <code>OptimisticLockType.ALL</code> update example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = entityManager.find( Person.class, 1L );
person.setCity( "Washington D.C." );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">UPDATE
    Person
SET
    city=?
WHERE
    id=?
    AND city=?
    AND country=?
    AND created_on=?
    AND "name"=?

-- binding parameter [1] as [VARCHAR] - [Washington D.C.]
-- binding parameter [2] as [BIGINT] - [1]
-- binding parameter [3] as [VARCHAR] - [New York]
-- binding parameter [4] as [VARCHAR] - [US]
-- binding parameter [5] as [TIMESTAMP] - [2016-11-16 16:05:12.876]
-- binding parameter [6] as [VARCHAR] - [John Doe]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>As you can see, all the columns of the associated database row are used in the <code>WHERE</code> clause.
If any column has changed after the row was loaded, there won&#8217;t be any match, and a <code>StaleStateException</code> or an <code>OptimisticLockException</code>
is going to be thrown.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>When using <code>OptimisticLockType.ALL</code>, you should also use <code>@DynamicUpdate</code> because the <code>UPDATE</code> statement must take into consideration all the entity property values.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="sect5">
<h6 id="entity-pojo-optlock-versionless-dirty">Versionless optimistic locking using <code>OptimisticLockType.DIRTY</code></h6>
<div class="paragraph">
<p>The <code>OptimisticLockType.DIRTY</code> differs from <code>OptimisticLockType.ALL</code>
in that it only takes into consideration the entity properties that have changed
since the entity was loaded in the currently running Persistence Context.</p>
</div>
<div id="locking-optimistic-lock-type-dirty-example" class="exampleblock">
<div class="title">Example 15. <code>OptimisticLockType.DIRTY</code> mapping example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">@Entity(name = "Person")
@OptimisticLocking(type = OptimisticLockType.DIRTY)
@DynamicUpdate
@SelectBeforeUpdate
public static class Person {

    @Id
    private Long id;

    @Column(name = "`name`")
    private String name;

    private String country;

    private String city;

    @Column(name = "created_on")
    private Timestamp createdOn;

    //Getters and setters are omitted for brevity
}</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>When you need to modify the <code>Person</code> entity above:</p>
</div>
<div id="locking-optimistic-lock-type-dirty-update-example" class="exampleblock">
<div class="title">Example 16. <code>OptimisticLockType.DIRTY</code> update example</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Person person = entityManager.find( Person.class, 1L );
person.setCity( "Washington D.C." );</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-SQL" data-lang="SQL">UPDATE
    Person
SET
    city=?
WHERE
    id=?
    and city=?

-- binding parameter [1] as [VARCHAR] - [Washington D.C.]
-- binding parameter [2] as [BIGINT] - [1]
-- binding parameter [3] as [VARCHAR] - [New York]</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>This time, only the database column that has changed was used in the <code>WHERE</code> clause.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The main advantage of <code>OptimisticLockType.DIRTY</code> over <code>OptimisticLockType.ALL</code>
and the default <code>OptimisticLockType.VERSION</code> used implicitly along with the <code>@Version</code> mapping,
is that it allows you to minimize the risk of <code>OptimisticLockException</code> across non-overlapping entity property changes.</p>
</div>
<div class="paragraph">
<p>When using <code>OptimisticLockType.DIRTY</code>, you should also use <code>@DynamicUpdate</code> because the <code>UPDATE</code> statement must take into consideration all the dirty entity property values,
and also the <code>@SelectBeforeUpdate</code> annotation so that detached entities are properly handled by the
<a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/Session.html#update-java.lang.Object-"><code>Session#update(entity)</code></a> operation.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2017-03-23 11:48:05 +01:00
</div>
</div>
</body>
</html>